<?php

namespace App\Http\Controllers\Api\v2;

use App\Http\Controllers\ApiController;
use App\Models\PostCatlog;
use App\Models\PostItem;

class PostController extends ApiController
{
    public function getItem(){
        $aid = $this->request->input('aid');
        $item = PostItem::find($aid);
        if ($item) {
            $item->image = image_url($item->image);
            return ajaxReturn([
                'item'=>$item,
                'catlog'=>$item->catlog,
                'images'=>$item->images->map(function ($image){
                    $image->thumb = image_url($image->thumb);
                    $image->image = image_url($image->image);
                    return $image;
                }),
                'content'=>$item->content
            ]);
        } else {
            return ajaxError(404, 'not found');
        }
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getItemList(){

        $offset = $this->request->input('offset');
        $count  = $this->request->input('count');
        $offset = $offset ? $offset : 0;
        $count  = $count ? $count : 20;

        $query = PostItem::available();

        $catid = $this->request->input('catid');
        if ($catid) $query = $query->where('catid', $catid);

        $items = $query->offset($offset)->limit($count)->orderByDesc('aid')
            ->get()->map(function ($item) {
                $item->key = "{$item->aid}";
                $item->image = image_url($item->image);
                $item->formatted_time = date('Y-m-d H:i', $item->created_at);
                return $item;
            });

        return ajaxReturn([
            'total_count'=>$query->count(),
            'offset'=>$offset,
            'count'=>$count,
            'items'=>$items
        ]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCatlog(){
        $catid = $this->request->input('catid');
        $catlog = PostCatlog::find($catid);
        $catlog->icon = image_url($catlog->icon);
        return ajaxReturn(['catlog'=>$catlog]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCatlogList(){
        $fid = intval($this->request->input('fid'));
        $items = PostCatlog::where('fid', $fid)->available()->orderBy('displayorder')
            ->orderBy('catid')->get()->map(function ($catlog){
                $catlog['icon'] = image_url($catlog['icon']);
                return $catlog;
            });

        return ajaxReturn(['items'=>$items]);
    }
}
